package bb.lanxing.activity.login

import android.R.attr
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.CheckBox
import android.widget.TextView
import bb.lanxing.App
import bb.lanxing.MainActivity
import bb.lanxing.R
import bb.lanxing.activity.agreement.AgreementActivity
import bb.lanxing.activity.interfaces.IGetAuthCodeView
import bb.lanxing.common.config.Constants.AUTHCODE_TYPE_BICI_FIND_PASSWORD
import bb.lanxing.common.config.Constants.AUTHCODE_TYPE_FORGET_PASSWORD
import bb.lanxing.common.config.Constants.AUTHCODE_TYPE_SET_PASSWORD
import bb.lanxing.common.config.Constants.AUTHCODE_TYPE_UNBIND_BICI
import bb.lanxing.common.config.Constants.INTERVAL_1_MIN
import bb.lanxing.common.config.Constants.INTERVAL_1_SEC
import bb.lanxing.common.config.UmengEventConst
import bb.lanxing.model.database.User
import bb.lanxing.model.event.MyProfileEvent
import bb.lanxing.mvp.presetner.GetAuthCodePresenterImpl
import bb.lanxing.mvp.presetner.i.IGetAuthCodePresenter
import bb.lanxing.network.BiCiCallback
import bb.lanxing.network.MyHttpClient
import bb.lanxing.util.BusProvider
import bb.lanxing.util.InputHelper
import bb.lanxing.util.Validator
import bb.lanxing.view.AccountInputView
import com.umeng.analytics.MobclickAgent
import org.json.JSONObject
import org.litepal.LitePal.where

class PhoneBindActivity : AgreementActivity(), IGetAuthCodeView {
    private lateinit var authcodeView: AccountInputView
    private lateinit var bindBtn: TextView
    private var canBack = false
    private lateinit var checkBoxUserAgreement: CheckBox
    private lateinit var emailBindBtn: TextView
    private lateinit var getAuthcodeBtn: TextView
    private lateinit var inputPhoneNumber: String
    private lateinit var mBindBtn: View
    private lateinit var mEmailBindBtn: View
    private lateinit var mGetAuthcodeBtn: View
    private lateinit var mTimer: CountDownTimer
    private lateinit var mVoiceView: View
    private lateinit var passwordLinearLayout: View
    private lateinit var passwordView: AccountInputView
    private lateinit var passwordViewAgain: AccountInputView
    private lateinit var phoneView: AccountInputView
    private lateinit var presenter: IGetAuthCodePresenter
    private var skip = false
    private lateinit var tvUserAgreement: TextView
    private var type = 0
    private var userMy: User? = null
    private lateinit var voiceView: TextView
    private var captcha = ""

    override fun onCreate(bundle: Bundle?) {
        super.onCreate(bundle)
        setContentView(R.layout.activity_phone_bind)
        bindView(window.decorView)
        setupActionBar(true)
        presenter = GetAuthCodePresenterImpl(this)
        type = intent.getIntExtra("type", 2)
        if (AUTHCODE_TYPE_UNBIND_BICI != type) {
            setTitle(R.string.mine_profile_desc_change_password)
            bindBtn.text = getString(R.string.club_main_club_config)
        } else {
            setTitle(R.string.mine_bind_title_phone_bind)
        }
        val intExtra = intent.getIntExtra("user_id", 0)
        skip = intent.getBooleanExtra("skip", false)
        canBack = intent.getBooleanExtra("canBack", true)
        userMy = User.getUserByUid(intExtra.toLong())
        if (type == 2) {
            passwordLinearLayout.visibility = View.GONE
        }
        val stringExtra = intent.getStringExtra("phone")
        inputPhoneNumber = stringExtra ?: ""
        if (!TextUtils.isEmpty(stringExtra)) {
            phoneView.text = inputPhoneNumber
        }
        bindBtn.isEnabled = false
        getAuthcodeBtn.isEnabled = false
        checkBoxUserAgreement.setOnCheckedChangeListener { _, _ ->
            setBindBtnStatus()
        }
        tvUserAgreement.text = getSpannableStringBuilder(this@PhoneBindActivity)
        tvUserAgreement.movementMethod = LinkMovementMethod.getInstance()
        phoneView.editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(editable: Editable) {}
            override fun beforeTextChanged(
                charSequence: CharSequence, i: Int, i2: Int, i3: Int
            ) {
            }

            override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
                setBindBtnStatus()
            }
        })
        passwordView.editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(editable: Editable) {}
            override fun beforeTextChanged(
                charSequence: CharSequence, i: Int, i2: Int, i3: Int
            ) {
            }

            override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
                setBindBtnStatus()
            }
        })
        passwordViewAgain.editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(editable: Editable) {}
            override fun beforeTextChanged(
                charSequence: CharSequence, i: Int, i2: Int, i3: Int
            ) {
            }

            override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
                setBindBtnStatus()
            }
        })

        authcodeView.editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(editable: Editable) {}
            override fun beforeTextChanged(
                charSequence: CharSequence, i: Int, i2: Int, i3: Int
            ) {
            }

            override fun onTextChanged(charSequence: CharSequence, i: Int, i2: Int, i3: Int) {
                setBindBtnStatus()
            }
        })
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_phone_bind, menu)
        menu.findItem(R.id.action_skip).setVisible(skip)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
        if (menuItem.itemId == R.id.action_skip) {
            startActivity(Intent(this, MainActivity::class.java))
            finish()
            return true
        }
        return super.onOptionsItemSelected(menuItem)
    }

    private fun setBindBtnStatus() {
        val length = phoneView.text.length
        val ret =
            length > 0 && (passwordView.text.isNotEmpty() && passwordViewAgain.text.isNotEmpty()) && checkBoxUserAgreement.isChecked
        getAuthcodeBtn.isEnabled = ret
        bindBtn.isEnabled = ret && authcodeView.text.isNotEmpty()
    }

    private fun bindBtn(view: View) {
        if (type == AUTHCODE_TYPE_UNBIND_BICI) {
            justBind()
        } else {
            bindWithPassword()
        }
    }

    private fun bindWithPassword() {
        val phone = phoneView.text
        val pwd = passwordView.text
        val pwdAgain = passwordViewAgain.text
        val authCode = authcodeView.text
        if (!Validator.isPhoneNumber(phone) || phone != inputPhoneNumber) {
            toast(R.string.mine_profile_phone_not_valid)
            phoneView.requestFocus()
        } else if (pwd.length < 6 || pwdAgain.length < 6) {
            toast(R.string.mine_profile_password_too_short)
            passwordView.requestFocus()
        } else if (pwd.length > 20 || pwdAgain.length > 20) {
            toast(R.string.mine_profile_password_too_long)
            passwordView.requestFocus()
        } else if (!pwd.equals(pwdAgain)) {
            toast(R.string.mine_profile_password_not_same)
        } else {
            try {
                val parseInt = authCode.toInt()
                showMyProgressDialog()
                hideInput()
                val callback = object : BiCiCallback(this) {
                    override fun onResponseString(str: String) {
                        toast(R.string.toast_operate_successful)
                        setResult(-1, Intent().putExtra("phoneNumber", phone))
                        if (null == userMy) {
                            userMy = where("phone=?", phone).findFirst(
                                User::class.java
                            )
                        }
                        userMy?.apply {
                            setPhone(phone)
                            havePassword = 1
                            save()
                        }
                        finish()
                        if (type == AUTHCODE_TYPE_BICI_FIND_PASSWORD) {
                            userMy?.let {
                                AccountLoginActivity.loginSuccess(it)
                            }
                        }
                        if (type != AUTHCODE_TYPE_SET_PASSWORD) {
                            startActivity(
                                Intent(
                                    this@PhoneBindActivity, MainActivity::class.java
                                )
                            )
                        }
                        finish()
                    }

                }
                if (type == AUTHCODE_TYPE_FORGET_PASSWORD) {
                    MyHttpClient.forgetPwd(callback, phone, parseInt, pwd)
                } else {
                    MyHttpClient.bindAccount(callback, phone, parseInt, pwd)
                }
            } catch (unused: NumberFormatException) {
                toast(R.string.mine_profile_authcode_not_valid)
                authcodeView.requestFocus()
            }
        }
    }

    private fun justBind() {
        val phone = phoneView.text
        val authCode = authcodeView.text
        if (!Validator.isPhoneNumber(phone) || phone != inputPhoneNumber) {
            toast(R.string.mine_profile_phone_not_valid)
            phoneView.requestFocus()
        } else if (TextUtils.isEmpty(authCode)) {
            toast(R.string.mine_profile_authcode_not_valid)
        } else {
            showMyProgressDialog()
            hideInput()
            MyHttpClient.bindPhone(object : BiCiCallback(this) {
                override fun onResponseString(str: String) {
                    toast(R.string.toast_operate_successful)
                    setResult(-1, Intent().putExtra("phoneNumber", attr.text))
                    if (null == userMy) {
                        userMy = where("phone=?", phone).findFirst(
                            User::class.java
                        )
                    }
                    userMy?.apply {
                        setPhone(phone)
                        save()
                    }
                    userMy?.let {
                        App.getContext().setSigninUser(it)
                    }
                    BusProvider.getInstance().post(MyProfileEvent(1))
                    finish()
                }

            }, phone, authCode)
            MobclickAgent.onEventValue(this, UmengEventConst.MINE_INFO_BIND_PHONE, null, 1)
        }
    }

    fun getAuthCodeBtnClick(view: View) {
        val text = phoneView.text
        if (Validator.isPhoneNumber(text)) {
            getAuthcodeBtn.isEnabled = false
            inputPhoneNumber = phoneView.text
            startCountDown()
            presenter.getAuthCode(text, 1, 0)
            return
        }
        toast(R.string.mine_profile_phone_not_valid)
    }

    fun voiceViewClick(view: View) {
        if (voiceView.isEnabled) {
            val text = phoneView.text
            if (Validator.isPhoneNumber(text)) {
                voiceView.isEnabled = false
                voiceView.setTextColor(Color.parseColor("#666666"))
                presenter.getAuthCode(text, 1, 1)
                return
            }
            toast(R.string.mine_profile_phone_not_valid)
        }
    }

    private fun startCountDown() {
        if (!this::mTimer.isInitialized) {
            mTimer = object : CountDownTimer(INTERVAL_1_MIN, INTERVAL_1_SEC) {
                override fun onTick(j: Long) {
                    getAuthcodeBtn.text = getString(
                        R.string.mine_profile_get_auth_code_time, (j / 1000).toString()
                    )
                }

                override fun onFinish() {
                    getAuthcodeBtn.setText(R.string.mine_login_get_message_code)
//                    authcodeView.text = captcha
                    getAuthcodeBtn.isEnabled = true
                }
            }
        }
        mTimer.start()
    }

    override fun onBackPressed() {
        if (canBack) {
            super.onBackPressed()
            cancelAndExit()
        }
    }

    override fun onHomeBack(): Boolean {
        if (canBack) {
            cancelAndExit()
        }
        return !canBack || super.onHomeBack()
    }

    private fun cancelAndExit() {
        hideInput()
        if (this::mTimer.isInitialized) {
            val countDownTimer = mTimer
            countDownTimer.cancel()
        }
        setResult(0)
    }

    private fun hideInput() {
        if (phoneView.editText.hasFocus()) {
            InputHelper.hideSoftInput(phoneView.editText)
        }
        if (passwordView.editText.hasFocus()) {
            InputHelper.hideSoftInput(passwordView.editText)
        }
        if (passwordViewAgain.editText.hasFocus()) {
            InputHelper.hideSoftInput(passwordViewAgain.editText)
        }
        if (authcodeView.editText.hasFocus()) {
            InputHelper.hideSoftInput(authcodeView.editText)
        }
    }

    override fun onGetAuthCodeResult(success: Boolean, type: Int) {
        if (type == 1) {
            if (success) {
                inputPhoneNumber = phoneView.text
                return
            }
            voiceView.isEnabled = true
            voiceView.setTextColor(Color.parseColor("#ff007ac2"))
        } else if (success) {
            inputPhoneNumber = phoneView.text
            startCountDown()
        } else {
            getAuthcodeBtn.isEnabled = true
        }
    }

    override fun onGetAuthCodeResult(jsonObject: JSONObject) {
        captcha = jsonObject.optString("captcha")
    }

    override fun onDestroy() {
        presenter.destroy()
        super.onDestroy()
    }

    private fun bindView(view: View) {
        phoneView = view.findViewById(R.id.phoneView)
        getAuthcodeBtn = view.findViewById(R.id.getAuthcodeBtn)
        authcodeView = view.findViewById(R.id.authcodeView)
        passwordViewAgain = view.findViewById(R.id.passwordViewAgain)
        passwordView = view.findViewById(R.id.passwordView)
        voiceView = view.findViewById(R.id.voiceView)
        emailBindBtn = view.findViewById(R.id.emailBindBtn)
        passwordLinearLayout = view.findViewById(R.id.ll_password)
        bindBtn = view.findViewById(R.id.bindBtn)
        checkBoxUserAgreement = view.findViewById(R.id.cb_login_user_agreement)
        tvUserAgreement = view.findViewById(R.id.tv_login_user_agreement)
        mBindBtn = view.findViewById(R.id.bindBtn)
        mEmailBindBtn = view.findViewById(R.id.emailBindBtn)
        mGetAuthcodeBtn = view.findViewById(R.id.getAuthcodeBtn)
        mVoiceView = view.findViewById(R.id.voiceView)
        mBindBtn.setOnClickListener(this::bindBtn)
        mGetAuthcodeBtn.setOnClickListener(this::getAuthCodeBtnClick)
        mVoiceView.setOnClickListener(this::voiceViewClick)
    }
}